import axios from "axios";
import { router } from "../router";

const api_url = (import.meta.env.VITE_SEREVER_API as string) || "/api/admin";

const http = axios.create({
  baseURL: api_url,
});

http.interceptors.request.use(
  (config: any) => {
    if (localStorage.token) {
      config.headers.Authorization =
        "Bearer " + localStorage.getItem("token") || "";
    }
    return config;
  },
  (e) => {
    return Promise.reject(e);
  }
);

http.interceptors.response.use(
  (res) => res,
  (e) => {
    if (e.response.status == 401) {
      router.push("/login");
      localStorage.clear();
    }
    return Promise.reject(e);
  }
);

async function upload(file: any): Promise<{ path: string; msg: string }> {
  const formData = new FormData();
  formData.append("file", file);
  const res = (
    await http.post(`uploads`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
  ).data;
  return { msg: res.msg, path: "/api" + res.data.path };
}

export { http, upload };
